package com.example.demo.api;

import com.example.demo.model.User;
import com.example.demo.model.UserMapper;
import com.sun.corba.se.impl.ior.OldJIDLObjectKeyTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @program: gobang
 * @author: JCM
 * @create: 2023-03-09 07:59
 * @description:
 **/
@RestController
public class UserAPI {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req) {
        //根据传递的 username 在数据库中查询用户
        // 如果能找到匹配的用户并且密码和数据库中的一致，则登陆成功
        User user = userMapper.selectByName(username);
        System.out.println("[login] username="+username);
        if(user == null || !password.equals(user.getPassword())) {
            // 登录失败
            System.out.println("登录失败");
            return new User();
        }
        HttpSession httpSession = req.getSession(true);
        httpSession.setAttribute("user",user);
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username,String password) {
        // 多吃插入同一个对象时，需要进行额外处理
        try {
            User user = new User();
            if(username.equals("") || password.equals("")) {
                // 用户名或密码为空时，不能注册
                return new User();
            }
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user);
            return user;
        } catch (org.springframework.dao.DuplicateKeyException e) {
            return new User();
        }


    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req) {
        try {
            HttpSession httpSession = req.getSession(false);
            User user = (User) httpSession.getAttribute("user");
            // 拿着这个 user 对象，去数据库中查找，找到最新的数据
            User newUser = userMapper.selectByName(user.getUsername());
            return newUser;
        } catch (NullPointerException e) {
            return new User();
        }

    }
}
